package com.wuyong.chapter6;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * 二分搜索树
 *
 * @param <E>
 */
public class BinarySearchTree<E extends Comparable<E>> {

    private class Node {
        private E e;
        private Node left, right;

        public Node(E e) {
            this.e = e;
            left = null;
            right = null;
        }
    }

    private Node root;
    private int size;

    public BinarySearchTree() {
        root = null;
        size = 0;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 添加元素 非递归方法
     *
     * @param e
     */
    public void add1(E e) {
        if (root == null) {
            root = new Node(e);
        }
        Node next = root;
        while (next != null) {
            if (e.compareTo(next.left.e) > 0) {
                next = next.right;
            } else {
                next = next.left;
            }
        }
        next = new Node(e);
        size++;
    }

    /**
     * 递归添加
     *
     * @param e
     */
    public void add_old(E e) {
        if (root == null) {
            root = new Node(e);
            size++;
        } else
            add_old(root, e);
    }

    //递归添加
    private void add_old(Node node, E e) {
        if (node.e.equals(e)) {
            return;
        }
        if (e.compareTo(node.e) > 0 && node.right == null) {
            node.right = new Node(e);
            size++;
            return;
        } else if (e.compareTo(node.e) < 0 && node.left == null) {
            node.left = new Node(e);
            size++;
            return;
        }
        if (e.compareTo(node.e) > 0) {
            add_old(node.right, e);

        } else {
            add_old(node.left, e);
        }
    }

    /**
     * 递归添加改进
     */
    public void add(E e) {
        root = add(root, e);
    }

    //向以node为根节点的二分搜索树中插入元素e， 递归算法
    //返回插入新节点后二分搜索树的根
    private Node add(Node node, E e) {
        if (node == null) {
            size++;
            return new Node(e);
        }
        if (e.compareTo(node.e) > 0) {
            node.right = add(node.right, e);
        } else if (e.compareTo(node.e) < 0) {
            node.left = add(node.left, e);
        }
        return node;
    }

    //二分搜索树中是否包含元素e
    public boolean contains(E e) {
        return contains(root, e);
    }

    private boolean contains(Node node, E e) {
        if (node == null) {
            return false;
        }
        if (e.compareTo(node.e) == 0) {
            return true;
        } else if (e.compareTo(node.e) > 0) {
            return contains(node.right, e);
        } else {
            return contains(node.left, e);
        }
    }

    public void preOrder() {
        preOrder(root);
    }

    /**
     * 前序遍历递归算法
     *
     * @param node
     */
    private void preOrder(Node node) {
        if (node == null) {
            return;
        }
        System.out.println(node.e);
        preOrder(node.left);
        preOrder(node.right);
    }

    /**
     * 中序遍历遍历递归算法
     */
    public void inOrder() {
        inOrder(root);
    }

    private void inOrder(Node node) {
        if (node == null) {
            return;
        }
        inOrder(node.left);
        System.out.println(node.e);
        inOrder(node.right);
    }

    /**
     * 后序遍历递归算法
     */
    public void postOrder() {
        postOrder(root);
    }

    private void postOrder(Node node) {
        if (node == null)
            return;
        postOrder(node.left);
        postOrder(node.right);
        System.out.println(node.e);
    }


    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        generateBSTString(root, 0, res);
        return res.toString();
    }

    // 生成以node为根节点，深度为depth的描述二叉树的字符串
    private void generateBSTString(Node node, int depth, StringBuilder res) {

        if (node == null) {
            res.append(generateDepthString(depth) + "null\n");
            return;
        }

        res.append(generateDepthString(depth) + node.e + "\n");
        generateBSTString(node.left, depth + 1, res);
        generateBSTString(node.right, depth + 1, res);
    }

    private String generateDepthString(int depth) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < depth; i++)
            res.append("--");
        return res.toString();
    }

    /**
     * 前序遍历非递归方法
     */
    public void preOrerWithStack() {
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.empty()) {
            Node cur = stack.pop();
            System.out.println(cur.e);

            if (cur.right != null)
                stack.push(cur.right);
            if (cur.left != null)
                stack.push(cur.left);
        }
    }

    /**
     * 层序遍历
     */
    public void levelOrder() {
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Node cur = queue.remove();
            System.out.println(cur.e);
            if (cur.left != null)
                queue.add(cur.left);
            if (cur.right != null)
                queue.add(cur.right);
        }
    }

    /**
     * 寻找最小值
     */
    public E getMinValue() {
        if (size == 0)
            throw new IllegalArgumentException("BST is empty!");
        return getMinValue(root).e;
    }

    private Node getMinValue(Node node) {
        if (node.left == null) {
            return node;
        }
        return getMinValue(node.left);
    }

    /**
     * 寻找最大值
     */
    public E getMaxValue() {
        if (size == 0)
            throw new IllegalArgumentException("BST is empty!");
        return getMaxValue(root).e;
    }

    private Node getMaxValue(Node node) {
        if (node.right == null) {
            return node;
        }
        return getMaxValue(node.right);
    }

    /**
     * 从二分搜索树种删除最小值所在节点，返回最小值
     * @return
     */
    public E removeMin() {
        E ret = getMinValue();
        root = removeMin(root);
        return ret;
    }
    // 删除掉以node为根节点的二分搜索树中的最小节点
    // 返回删除节点后新的二分搜索树的根
    private Node removeMin(Node node) {
        if (node.left == null) {
            Node rightNode = node.right;
            node.right = null;
            size --;
            return rightNode;
        }
        node.left = removeMin(node.left);
        return  node;
    }

    /**
     * 从二分搜索树种删除最大值所在节点，返回最大值
     * @return
     */
    public E removeMax() {
        E ret = getMaxValue();
        root = removeMax(root);
        return ret;
    }
    // 删除掉以node为根节点的二分搜索树中的最大节点
    // 返回删除节点后新的二分搜索树的根
    private Node removeMax(Node node) {
        if (node.right == null) {
            Node leftNode = node.left;
            node.left = null;
            size --;
            return leftNode;
        }
        node.right = removeMax(node.right);
        return  node;
    }

    public void remove(E e) {
        root = remove(root, e);
    }
    //Hibbard Deletion
    public Node remove(Node node, E e) {
        if( node == null )
            return null;

        if( e.compareTo(node.e) < 0 ){
            node.left = remove(node.left , e);
            return node;
        }
        else if(e.compareTo(node.e) > 0 ){
            node.right = remove(node.right, e);
            return node;
        }
        else{   // e.compareTo(node.e) == 0

            // 待删除节点左子树为空的情况
            if(node.left == null){
                Node rightNode = node.right;
                node.right = null;
                size --;
                return rightNode;
            }

            // 待删除节点右子树为空的情况
            if(node.right == null){
                Node leftNode = node.left;
                node.left = null;
                size --;
                return leftNode;
            }

            // 待删除节点左右子树均不为空的情况

            // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
            // 用这个节点顶替待删除节点的位置
            Node successor = getMinValue(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;

            node.left = node.right = null;

            return successor;
        }
    }


}
